import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog, font
import itertools
import os
from datetime import datetime
from PIL import Image, ImageDraw, ImageFont  # 导入PIL库用于生成图片

class Lottery9FromN:
    def __init__(self, root):
        # 初始化主窗口
        self.root = root
        self.root.title("胜负彩任9组合生成器")
        self.root.geometry("1400x900")
        self.root.minsize(1200, 800)

        # 数据初始化
        self.matches = self._init_match_data()  # 14场比赛数据
        self.match_checks = {}  # 场次勾选状态: {match_id: BooleanVar}
        self.match_choices = {}  # 每场比赛的胜平负选择: {match_id: {'3': BooleanVar, ...}}
        self.generated_combinations = []  # 生成的9场组合

        # 创建界面
        self.create_widgets()

    def _init_match_data(self):
        """初始化14场比赛数据"""
        return [
            {"id": 1, "league": "欧冠", "time": "08-13 00:00", "home": "卡拉巴赫", "away": "斯肯迪亚",
             "odds3": 1.38, "odds1": 4.79, "odds0": 8.72},
            {"id": 2, "league": "欧冠", "time": "08-13 01:00", "home": "哥本哈根", "away": "马尔默",
             "odds3": 1.72, "odds1": 3.49, "odds0": 4.93},
            {"id": 3, "league": "欧冠", "time": "08-13 01:00", "home": "费内巴切", "away": "费耶诺德",
             "odds3": 1.83, "odds1": 3.80, "odds0": 3.87},
            {"id": 4, "league": "欧冠", "time": "08-13 01:00", "home": "比尔森", "away": "流浪者",
             "odds3": 1.91, "odds1": 3.81, "odds0": 3.71},
            {"id": 5, "league": "欧冠", "time": "08-13 01:30", "home": "布鲁日", "away": "萨茨堡",
             "odds3": 1.86, "odds1": 3.82, "odds0": 4.12},
            {"id": 6, "league": "欧冠", "time": "08-13 02:15", "home": "费伦茨", "away": "卢多戈雷茨",
             "odds3": 1.91, "odds1": 3.30, "odds0": 3.75},
            {"id": 7, "league": "欧冠", "time": "08-13 02:15", "home": "布拉迪斯拉发", "away": "阿拉木图",
             "odds3": 1.70, "odds1": 3.95, "odds0": 4.27},
            {"id": 8, "league": "欧冠", "time": "08-13 03:00", "home": "本菲卡", "away": "尼斯",
             "odds3": 1.68, "odds1": 3.90, "odds0": 5.00},
            {"id": 9, "league": "欧超杯", "time": "08-14 03:00", "home": "巴黎圣日耳曼", "away": "热刺",
             "odds3": 1.45, "odds1": 4.72, "odds0": 6.04},
            {"id": 10, "league": "欧协联", "time": "08-14 00:00", "home": "伊斯坦布尔", "away": "维京",
             "odds3": 1.74, "odds1": 3.91, "odds0": 4.03},
            {"id": 11, "league": "欧罗巴", "time": "08-14 02:00", "home": "西汉姆联", "away": "维堡",
             "odds3": 1.32, "odds1": 4.85, "odds0": 9.25},
            {"id": 12, "league": "欧罗巴", "time": "08-14 02:30", "home": "罗马", "away": "谢里夫",
             "odds3": 1.41, "odds1": 4.52, "odds0": 7.63},
            {"id": 13, "league": "欧罗巴", "time": "08-14 03:00", "home": "曼联", "away": "皇家社会",
             "odds3": 1.85, "odds1": 3.65, "odds0": 4.02},
            {"id": 14, "league": "欧罗巴", "time": "08-14 03:00", "home": "勒沃库森", "away": "赫根",
             "odds3": 1.52, "odds1": 4.05, "odds0": 6.35}
        ]

    def create_widgets(self):
        # 顶部信息栏
        top_frame = tk.Frame(self.root, bg="#f5f5f5", height=60)
        top_frame.pack(fill=tk.X, padx=10, pady=5)
        top_frame.pack_propagate(False)

        # 期号信息
        self.issue_var = tk.StringVar(value=f"第{datetime.now().strftime('%Y%m%d')}期 胜负彩 任9")
        tk.Label(top_frame, textvariable=self.issue_var, bg="#f5f5f5",
                 font=("SimHei", 12, "bold")).pack(side=tk.LEFT, padx=20, pady=10)

        # 选择统计
        self.selection_stats = tk.StringVar(value="已勾选场次: 0 | 可生成组合数: 0 | 预计总注数: 0")
        tk.Label(top_frame, textvariable=self.selection_stats, bg="#f5f5f5",
                 font=("SimHei", 10)).pack(side=tk.LEFT, padx=50)

        # 操作按钮
        btn_frame = tk.Frame(top_frame, bg="#f5f5f5")
        btn_frame.pack(side=tk.RIGHT, padx=20)

        tk.Button(btn_frame, text="生成9场组合", command=self.generate_combinations,
                  bg="#4CAF50", fg="white", padx=15).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="导出组合", command=self.export_combinations,
                  bg="#2196F3", fg="white", padx=15).pack(side=tk.LEFT, padx=5)
        # 导出图片按钮
        tk.Button(btn_frame, text="导出组合图片", command=self.export_combinations_as_images,
                  bg="#FF9800", fg="white", padx=15).pack(side=tk.LEFT, padx=5)
        tk.Button(btn_frame, text="清空选择", command=self.clear_all,
                  bg="#f44336", fg="white", padx=15).pack(side=tk.LEFT, padx=5)

        # 主内容区
        content_frame = tk.Frame(self.root)
        content_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)

        # 左侧比赛列表区域
        left_frame = tk.Frame(content_frame, width=700)
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        # 比赛列表标题行
        header_frame = tk.Frame(left_frame, bg="#e0e0e0", height=30)
        header_frame.pack(fill=tk.X, padx=5)
        header_frame.pack_propagate(False)

        # 标题列
        tk.Label(header_frame, text="勾选", bg="#e0e0e0", width=5, borderwidth=1, relief="solid").grid(row=0, column=0)
        tk.Label(header_frame, text="序号", bg="#e0e0e0", width=5, borderwidth=1, relief="solid").grid(row=0, column=1)
        tk.Label(header_frame, text="联赛", bg="#e0e0e0", width=8, borderwidth=1, relief="solid").grid(row=0, column=2)
        tk.Label(header_frame, text="时间", bg="#e0e0e0", width=10, borderwidth=1, relief="solid").grid(row=0, column=3)
        tk.Label(header_frame, text="对阵", bg="#e0e0e0", width=25, borderwidth=1, relief="solid").grid(row=0, column=4)
        tk.Label(header_frame, text="胜(3)", bg="#e0e0e0", width=8, borderwidth=1, relief="solid").grid(row=0, column=5)
        tk.Label(header_frame, text="平(1)", bg="#e0e0e0", width=8, borderwidth=1, relief="solid").grid(row=0, column=6)
        tk.Label(header_frame, text="负(0)", bg="#e0e0e0", width=8, borderwidth=1, relief="solid").grid(row=0, column=7)

        # 比赛列表区域（带滚动条）
        list_frame = tk.Frame(left_frame)
        list_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=2)

        canvas = tk.Canvas(list_frame)
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=canvas.yview)
        self.match_list_frame = ttk.Frame(canvas)

        self.match_list_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )

        canvas.create_window((0, 0), window=self.match_list_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)

        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # 右侧组合结果区域
        right_frame = tk.Frame(content_frame, width=700, bg="#f0f0f0")
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5)

        # 组合结果标题
        tk.Label(right_frame, text="9场组合及金额明细", bg="#e0e0e0", font=("SimHei", 11, "bold"),
                 height=2).pack(fill=tk.X)

        # 组合统计信息
        stats_frame = tk.Frame(right_frame, bg="#ffffff", height=30)
        stats_frame.pack(fill=tk.X, padx=5, pady=5)
        stats_frame.pack_propagate(False)

        self.total_stats_var = tk.StringVar(value="总组合数: 0 | 总注数: 0 | 总金额: 0元")
        tk.Label(stats_frame, textvariable=self.total_stats_var, bg="#ffffff",
                 font=("SimHei", 10, "bold"), fg="#d32f2f").pack(side=tk.LEFT, padx=10)

        # 组合列表（带滚动条）
        self.combo_text = scrolledtext.ScrolledText(right_frame, wrap=tk.WORD, font=("SimHei", 10))
        self.combo_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
        self.combo_text.config(state=tk.DISABLED)

        # 初始化比赛列表
        self.init_match_list()

    def init_match_list(self):
        """初始化比赛列表"""
        # 清空现有内容
        for widget in self.match_list_frame.winfo_children():
            widget.destroy()

        # 为每场比赛创建UI元素
        for idx, match in enumerate(self.matches):
            # 交替行背景色
            bg_color = "#f9f9f9" if idx % 2 == 0 else "#ffffff"

            # 创建行框架
            row_frame = tk.Frame(self.match_list_frame, bg=bg_color, height=30)
            row_frame.pack(fill=tk.X, pady=1)
            row_frame.pack_propagate(False)

            # 勾选场次
            match_check = tk.BooleanVar(value=False)
            self.match_checks[match["id"]] = match_check
            tk.Checkbutton(row_frame, variable=match_check, bg=bg_color,
                           command=self.update_selection_stats).grid(row=0, column=0, sticky="nsew")

            # 序号
            tk.Label(row_frame, text=str(match["id"]), bg=bg_color, width=5,
                     borderwidth=1, relief="solid").grid(row=0, column=1, sticky="nsew")

            # 联赛
            tk.Label(row_frame, text=match["league"], bg=bg_color, width=8,
                     borderwidth=1, relief="solid").grid(row=0, column=2, sticky="nsew")

            # 时间
            tk.Label(row_frame, text=match["time"], bg=bg_color, width=10,
                     borderwidth=1, relief="solid").grid(row=0, column=3, sticky="nsew")

            # 对阵
            vs_text = f"{match['home']} vs {match['away']}"
            tk.Label(row_frame, text=vs_text, bg=bg_color, width=25,
                     borderwidth=1, relief="solid", anchor="w").grid(row=0, column=4, sticky="nsew")

            # 胜平负多选
            choices = {
                "3": tk.BooleanVar(value=False),
                "1": tk.BooleanVar(value=False),
                "0": tk.BooleanVar(value=False)
            }
            self.match_choices[match["id"]] = choices

            # 胜（3）
            frame3 = tk.Frame(row_frame, bg="#ffebee", borderwidth=1, relief="solid")
            frame3.grid(row=0, column=5, sticky="nsew")
            tk.Checkbutton(frame3, text=f"{match['odds3']}", variable=choices["3"],
                           bg="#ffebee", command=self.update_selection_stats).pack(fill=tk.BOTH, expand=True)

            # 平（1）
            frame1 = tk.Frame(row_frame, bg="#fff8e1", borderwidth=1, relief="solid")
            frame1.grid(row=0, column=6, sticky="nsew")
            tk.Checkbutton(frame1, text=f"{match['odds1']}", variable=choices["1"],
                           bg="#fff8e1", command=self.update_selection_stats).pack(fill=tk.BOTH, expand=True)

            # 负（0）
            frame0 = tk.Frame(row_frame, bg="#e8f5e9", borderwidth=1, relief="solid")
            frame0.grid(row=0, column=7, sticky="nsew")
            tk.Checkbutton(frame0, text=f"{match['odds0']}", variable=choices["0"],
                           bg="#e8f5e9", command=self.update_selection_stats).pack(fill=tk.BOTH, expand=True)

            # 配置列权重
            for i in range(8):
                row_frame.grid_columnconfigure(i, weight=1)

    def get_checked_matches(self):
        """获取所有勾选的场次"""
        return [match for match in self.matches if self.match_checks[match["id"]].get()]

    def update_selection_stats(self):
        """实时更新勾选统计"""
        checked_matches = self.get_checked_matches()
        checked_count = len(checked_matches)

        # 计算组合数 C(n,9)
        combo_count = self.combination(checked_count, 9) if 9 <= checked_count <=14 else 0

        # 估算总注数（实际生成时精确计算）
        total_bets = 0
        if combo_count > 0:
            # 计算平均每场选择的结果数
            avg_choices = 0
            valid_count = 0
            for match in checked_matches:
                choices = self.match_choices[match["id"]]
                cnt = sum([choices["3"].get(), choices["1"].get(), choices["0"].get()])
                if cnt > 0:
                    avg_choices += cnt
                    valid_count += 1

            if valid_count > 0:
                avg_choices /= valid_count
                # 估算总注数 = 组合数 × (平均选择数)^9
                total_bets = int(combo_count * (avg_choices **9))

        self.selection_stats.set(f"已勾选场次: {checked_count} | 可生成组合数: {combo_count} | 预计总注数: {total_bets}")

    def generate_combinations(self):
        """生成所有9场组合并计算金额"""
        checked_matches = self.get_checked_matches()
        checked_count = len(checked_matches)

        # 检查勾选数量
        if not (9 <= checked_count <= 14):
            messagebox.showinfo("提示", f"请勾选9-14场比赛！当前已勾选{checked_count}场")
            return

        # 检查每场是否至少选择了一个结果
        for match in checked_matches:
            choices = self.match_choices[match["id"]]
            if not (choices["3"].get() or choices["1"].get() or choices["0"].get()):
                messagebox.showinfo("提示", f"场次 {match['id']}（{match['home']} vs {match['away']}）未选择任何结果！")
                return

        # 生成所有9场组合
        self.generated_combinations = list(itertools.combinations(checked_matches, 9))
        self.display_combinations()

    def display_combinations(self):
        """显示所有组合及金额"""
        self.combo_text.config(state=tk.NORMAL)
        self.combo_text.delete(1.0, tk.END)

        total_bets = 0  # 总注数
        total_amount = 0  # 总金额

        for i, combo in enumerate(self.generated_combinations, 1):
            # 按场次ID排序
            sorted_combo = sorted(combo, key=lambda x: x["id"])
            match_ids = [str(m["id"]) for m in sorted_combo]

            # 计算该组合的注数
            combo_bets = 1
            for match in sorted_combo:
                choices = self.match_choices[match["id"]]
                select_count = sum([choices["3"].get(), choices["1"].get(), choices["0"].get()])
                combo_bets *= select_count

            # 计算该组合的金额（每注2元）
            combo_amount = combo_bets * 2
            total_bets += combo_bets
            total_amount += combo_amount

            # 显示组合信息
            self.combo_text.insert(tk.END, f"组合 {i}: 场次 {', '.join(match_ids)} | 注数: {combo_bets} | 金额: {combo_amount}元\n")
            self.combo_text.insert(tk.END, "\n")

        # 更新总统计
        self.total_stats_var.set(f"总组合数: {len(self.generated_combinations)} | 总注数: {total_bets} | 总金额: {total_amount}元")
        self.combo_text.config(state=tk.DISABLED)

    def export_combinations(self):
        """导出组合结果到文本文件"""
        if not self.generated_combinations:
            messagebox.showinfo("提示", "请先生成组合！")
            return

        # 获取保存路径
        current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
        default_filename = f"任9组合_{current_time}.txt"
        file_path = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")],
            initialfile=default_filename
        )

        if not file_path:
            return

        try:
            with open(file_path, "w", encoding="utf-8") as f:
                f.write(f"胜负彩任9组合 - {self.issue_var.get()}\n")
                f.write(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write(f"{self.total_stats_var.get()}\n\n")

                for i, combo in enumerate(self.generated_combinations, 1):
                    sorted_combo = sorted(combo, key=lambda x: x["id"])
                    match_ids = [str(m["id"]) for m in sorted_combo]

                    combo_bets = 1
                    for match in sorted_combo:
                        choices = self.match_choices[match["id"]]
                        select_count = sum([choices["3"].get(), choices["1"].get(), choices["0"].get()])
                        combo_bets *= select_count

                    combo_amount = combo_bets * 2

                    f.write(f"组合 {i}: 场次 {', '.join(match_ids)} | 注数: {combo_bets} | 金额: {combo_amount}元\n")
                    f.write("  选择详情:\n")

                    for match in sorted_combo:
                        choices = self.match_choices[match["id"]]
                        selected = []
                        if choices["3"].get():
                            selected.append(f"胜(3, {match['odds3']})")
                        if choices["1"].get():
                            selected.append(f"平(1, {match['odds1']})")
                        if choices["0"].get():
                            selected.append(f"负(0, {match['odds0']})")

                        f.write(f"  场次{match['id']}: {match['home']} vs {match['away']} → {', '.join(selected)}\n")
                    f.write("\n")

            messagebox.showinfo("成功", f"组合已导出到:\n{file_path}")
        except Exception as e:
            messagebox.showerror("错误", f"导出失败: {str(e)}")

    # 导出组合为图片（仅选中项为红色）
    def export_combinations_as_images(self):
        """导出所有组合为图片文件，仅将选中的胜平负选项设置为红色"""
        if not self.generated_combinations:
            messagebox.showinfo("提示", "请先生成组合！")
            return

        # 让用户选择保存目录
        save_dir = filedialog.askdirectory(title="选择保存图片的文件夹")
        if not save_dir:
            return

        # 创建图片保存子目录
        current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
        combo_dir = os.path.join(save_dir, f"任9组合图片_{current_time}")
        os.makedirs(combo_dir, exist_ok=True)

        try:
            # 尝试加载中文字体，确保中文正常显示
            try:
                # 尝试使用系统中的黑体字体
                title_font = ImageFont.truetype("simhei.ttf", 22)
                subtitle_font = ImageFont.truetype("simhei.ttf", 18)
                normal_font = ImageFont.truetype("simhei.ttf", 16)
                small_font = ImageFont.truetype("simhei.ttf", 14)
            except:
                # 如果找不到指定字体，使用默认字体
                title_font = ImageFont.load_default()
                subtitle_font = ImageFont.load_default()
                normal_font = ImageFont.load_default()
                small_font = ImageFont.load_default()

            # 为每个组合生成一张图片
            for i, combo in enumerate(self.generated_combinations, 1):
                # 排序组合中的比赛
                sorted_combo = sorted(combo, key=lambda x: x["id"])
                match_ids = [str(m["id"]) for m in sorted_combo]

                # 计算注数和金额
                combo_bets = 1
                for match in sorted_combo:
                    choices = self.match_choices[match["id"]]
                    select_count = sum([choices["3"].get(), choices["1"].get(), choices["0"].get()])
                    combo_bets *= select_count
                combo_amount = combo_bets * 2

                # 创建图片（宽度1000，高度根据比赛数量动态调整）
                img_height = 200 + len(sorted_combo) * 100
                # 整体保持浅色背景
                image = Image.new('RGB', (1000, img_height), color='#f8f9fa')
                draw = ImageDraw.Draw(image)

                # 绘制标题区域
                draw.rectangle([(0, 0), (1000, 150)], fill='#e9ecef')
                draw.text((50, 40), f"胜负彩任9组合 - {self.issue_var.get()}", font=title_font, fill='#2d3436')
                draw.text((50, 80), f"组合 {i}: 场次 {', '.join(match_ids)} | 注数: {combo_bets} | 金额: {combo_amount}元",
                          font=subtitle_font, fill='#2d3436')
                draw.line([(50, 130), (950, 130)], fill='#adb5bd', width=2)

                # 绘制每场比赛的详情
                y_position = 160
                for idx, match in enumerate(sorted_combo, 1):
                    # 绘制场次背景
                    bg_color = '#ffffff' if idx % 2 == 0 else '#f1f3f5'
                    draw.rectangle([(30, y_position), (970, y_position + 90)], fill=bg_color)
                    draw.line([(30, y_position + 90), (970, y_position + 90)], fill='#e9ecef', width=1)

                    # 绘制场次信息
                    match_header = f"场次{match['id']} [{match['league']}] {match['time']}"
                    draw.text((50, y_position + 10), match_header, font=normal_font, fill='#2d3436')

                    # 绘制对阵信息
                    vs_text = f"{match['home']}  vs  {match['away']}"
                    draw.text((50, y_position + 40), vs_text, font=normal_font, fill='#2d3436')

                    # 绘制胜平负选择区域
                    # 胜(3) - 未选中保持浅红，选中变为红色
                    win_rect = [(600, y_position + 15), (700, y_position + 65)]
                    # 关键修改：仅选中时使用红色背景
                    win_bg = '#e74c3c' if self.match_choices[match["id"]]["3"].get() else '#ffebee'
                    win_text_color = 'white' if self.match_choices[match["id"]]["3"].get() else '#e74c3c'
                    draw.rectangle(win_rect, fill=win_bg)
                    draw.rectangle(win_rect, outline='#dee2e6', width=2)
                    draw.text((650, y_position + 35), "3\n胜", font=normal_font,
                              fill=win_text_color, anchor='mm')
                    draw.text((650, y_position + 70), f"{match['odds3']}", font=small_font,
                              fill='#e74c3c', anchor='mm')

                    # 平(1) - 未选中保持浅黄，选中变为红色
                    draw_rect = [(720, y_position + 15), (820, y_position + 65)]
                    # 关键修改：仅选中时使用红色背景
                    draw_bg = '#e74c3c' if self.match_choices[match["id"]]["1"].get() else '#fff8e1'
                    draw_text_color = 'white' if self.match_choices[match["id"]]["1"].get() else '#f39c12'
                    draw.rectangle(draw_rect, fill=draw_bg)
                    draw.rectangle(draw_rect, outline='#dee2e6', width=2)
                    draw.text((770, y_position + 35), "1\n平", font=normal_font,
                              fill=draw_text_color, anchor='mm')
                    draw.text((770, y_position + 70), f"{match['odds1']}", font=small_font,
                              fill='#f39c12', anchor='mm')

                    # 负(0) - 未选中保持浅绿，选中变为红色
                    lose_rect = [(840, y_position + 15), (940, y_position + 65)]
                    # 关键修改：仅选中时使用红色背景
                    lose_bg = '#e74c3c' if self.match_choices[match["id"]]["0"].get() else '#e8f5e9'
                    lose_text_color = 'white' if self.match_choices[match["id"]]["0"].get() else '#27ae60'
                    draw.rectangle(lose_rect, fill=lose_bg)
                    draw.rectangle(lose_rect, outline='#dee2e6', width=2)
                    draw.text((890, y_position + 35), "0\n负", font=normal_font,
                              fill=lose_text_color, anchor='mm')
                    draw.text((890, y_position + 70), f"{match['odds0']}", font=small_font,
                              fill='#27ae60', anchor='mm')

                    y_position += 90  # 下一场比赛的Y坐标

                # 绘制底部信息
                draw.line([(50, y_position + 20), (950, y_position + 20)], fill='#adb5bd', width=1)
                draw.text((50, y_position + 40), f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
                          font=small_font, fill='#6c757d')

                # 保存图片
                img_path = os.path.join(combo_dir, f"组合_{i}.png")
                image.save(img_path)

            messagebox.showinfo("成功", f"所有组合图片已导出到:\n{combo_dir}")
        except Exception as e:
            messagebox.showerror("错误", f"导出图片失败: {str(e)}")

    def clear_all(self):
        """清空所有选择"""
        # 清空场次勾选
        for var in self.match_checks.values():
            var.set(False)

        # 清空胜平负选择
        for choices in self.match_choices.values():
            choices["3"].set(False)
            choices["1"].set(False)
            choices["0"].set(False)

        # 清空组合结果
        self.generated_combinations = []
        self.combo_text.config(state=tk.NORMAL)
        self.combo_text.delete(1.0, tk.END)
        self.combo_text.config(state=tk.DISABLED)

        # 更新统计
        self.update_selection_stats()
        self.total_stats_var.set("总组合数: 0 | 总注数: 0 | 总金额: 0元")

    @staticmethod
    def combination(n, k):
        """计算组合数 C(n,k)"""
        if k < 0 or k > n:
            return 0
        if k == 0 or k == n:
            return 1
        k = min(k, n - k)
        result = 1
        for i in range(1, k + 1):
            result = result * (n - k + i) // i
        return result

if __name__ == "__main__":
    # 确保中文显示正常
    root = tk.Tk()
    # 设置中文字体支持
    try:
        default_font = font.nametofont("TkDefaultFont")
        default_font.configure(family="SimHei", size=10)
        root.option_add("*Font", default_font)
    except:
        pass  # 字体设置失败时使用默认字体

    app = Lottery9FromN(root)
    root.mainloop()
